package com.zlt.utils;

import java.lang.reflect.Field;
import java.util.Map;
import java.util.Set;

public class BeanUtil {

    /**
     * 从请求中解析指定的参数 封装成对象
     * 这里暂时不考虑一个参数名多个参数值的情况
     * @param clazz
     * @param map
     * @param <T>
     * @return
     */
    public static <T> T resolveBean(Class<T> clazz, Map<String, String[]> map){

        Set<Map.Entry<String, String[]>> entries = map.entrySet();
        T obj = null;
        try {
            obj = clazz.newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        for (Map.Entry<String, String[]> entry : entries) {
            String key = entry.getKey();
            String[] value = entry.getValue();
            //根据key找到对应的属性
            try {
                Field declaredField = clazz.getDeclaredField(key);
                declaredField.setAccessible(true);
                Class<?> type = declaredField.getType();
                if(type == int.class || type == Integer.class){
                    declaredField.set(obj, Integer.parseInt(value[0]));
                } else if(type == double.class || type == Double.class){
                    declaredField.set(obj, Double.parseDouble(value[0]));
                } else {
                    if(StringUtil.isNotNull(value[0]))
                    declaredField.set(obj,value[0]);
                }
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return obj;
    }
}
